package com.center.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.aimer.common.R;
import com.blankj.utilcode.util.LogUtils;
import com.center.model.ViewModelQQLogin;
import com.center.util.Util;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.open.log.SLog;
import com.tencent.tauth.DefaultUiListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import base.QActivity;
import constant.AppConstants;

import static com.tencent.connect.common.Constants.KEY_ENABLE_SHOW_DOWNLOAD_URL;
import static com.tencent.connect.common.Constants.KEY_QRCODE;
import static com.tencent.connect.common.Constants.KEY_RESTORE_LANDSCAPE;
import static com.tencent.connect.common.Constants.KEY_SCOPE;

public class LoginActivity extends QActivity {

    private static Tencent mTencent;

    private ImageView imageView;
    private ViewModelQQLogin viewModelQQLogin;


    @Override
    public int getLayoutRes() {
        return R.layout.login_acitvity;
    }

    @Override
    public void initView() {
        //不加这个会加载不出来
        Tencent.setIsPermissionGranted(true);
        mTencent = Tencent.createInstance(AppConstants.APP_ID,this);
        imageView = findViewById(R.id.ivpic);
        viewModelQQLogin = ViewModelQQLogin.getInstance();

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTencent.logout(LoginActivity.this);
            }
        });
    }


    @Override
    public void initData() {
        JSONObject jsonObject = mTencent.loadSession(AppConstants.APP_ID);
        LogUtils.i(TAG, "initLocalData: " + jsonObject);
        if (jsonObject != null) {

            initOpenidAndToken(jsonObject);
            if (TextUtils.isEmpty(mTencent.getAccessToken())) {
                mTencent.initSessionCache(mTencent.loadSession(AppConstants.APP_ID));
            }
        }

        updateUserInfo();
        login();
    }

    public void login() {

        if (!mTencent.isSessionValid()) {
            HashMap<String, Object> params = new HashMap<String, Object>();
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
                params.put(KEY_RESTORE_LANDSCAPE, true);
            }
            params.put(KEY_SCOPE, "all");
            params.put(KEY_QRCODE, true);
            params.put(KEY_ENABLE_SHOW_DOWNLOAD_URL, true);
            mTencent.login(this, loginListener, params);
        }

    }


    @Override
    public void initListener() {

    }

    @Override
    public void networkMessage() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 自V3.3.0 必须，否则无法呼出 loginListener的onComplete
        Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
    }


    public static void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }


    private void updateUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            IUiListener listener = new DefaultUiListener() {

                @Override
                public void onError(UiError e) {

                }

                @Override
                public void onComplete(final Object responsex) {
                    LogUtils.d(TAG, "updateUserInfo" + responsex);
                    JSONObject response = (JSONObject) responsex;
                    if (response.has("nickname")) {
                        try {

                            viewModelQQLogin.getQQName().setValue(response.getString("nickname"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    new Thread() {
                        @Override
                        public void run() {
                            JSONObject json = (JSONObject) response;
                            if (json.has("figureurl")) {
                                try {
                                    Bitmap bitmap = Util.getbitmap(json.getString("figureurl_qq_2"));
                                    imageView.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            imageView.setImageBitmap(bitmap);
                                            viewModelQQLogin.getAvatarUrl().setValue(bitmap);
                                            finish();
                                        }
                                    }, 100);
                                } catch (JSONException e) {
                                    SLog.e(TAG, "Util.getBitmap() jsonException : " + e.getMessage());
                                }

                            }
                        }
                    }.start();


                }

                @Override
                public void onCancel() {

                }
            };
            UserInfo info = new UserInfo(this, mTencent.getQQToken());
            info.getUserInfo(listener);
        }
    }

    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            LogUtils.d(TAG, "SDKQQAgentPref", "AuthorSwitch_SDK:" + SystemClock.elapsedRealtime());
            initOpenidAndToken(values);
            updateUserInfo();
        }
    };


    private class BaseUiListener extends DefaultUiListener {

        @Override
        public void onComplete(Object response) {

            LogUtils.d(TAG, "加分加分" + response);
            if (null == response) {
                LogUtils.d(TAG, "返回为空", "登录失败");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (jsonResponse.length() == 0) {
                LogUtils.d(TAG, "返回为空", "登录失败");
                return;
            }
            LogUtils.d(TAG, "登录成功", response.toString());

            doComplete((JSONObject) response);


            JSONObject json = (JSONObject) response;
            if (json.has("nickname")) {
                try {
                    viewModelQQLogin.getQQName().setValue(json.getString("nickname"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if (json.has("figureurl")) {
                Bitmap bitmap = null;
                try {
                    bitmap = Util.getbitmap(json.getString("figureurl_qq_2"));
                } catch (JSONException e) {
                    SLog.e(TAG, "Util.getBitmap() jsonException : " + e.getMessage());
                }
                imageView.setImageBitmap(bitmap);
                viewModelQQLogin.getAvatarUrl().setValue(bitmap);

                finish();

            }


        }

        protected void doComplete(JSONObject values) {
            LogUtils.d(TAG, "doComplete:" + values);
        }

        @Override
        public void onError(UiError e) {
            LogUtils.d(TAG, "onError:" + e.toString());
        }

        @Override
        public void onCancel() {
            LogUtils.d(TAG, "onCancel");
        }
    }
}
